//
//  DropDetailVC.swift
//  Drop
//
//  Created by zhuxuhong on 2018/3/17.
//  Copyright © 2018年 zhuxuhong. All rights reserved.
//

import UIKit
import Dialog

class DropContentCell: UITableViewCell {
    @IBOutlet weak var textView: UITextView!
    
}

class DropDetailVC: UIViewController {
	@IBOutlet weak var authorAvatarIV: UIImageView!
	@IBOutlet weak var authorNameLabel: UILabel!
	@IBOutlet weak var dateLabel: UILabel!
	@IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var toolbar: UIToolbar!
    @IBOutlet var toolbarButtons: [UIButton]!
    
    var drop = Drop()
    
    fileprivate lazy var comments = Comment.sampleData()
    
	fileprivate lazy var contentHeight: CGFloat = {
		let margins = UIEdgeInsetsMake(8, 8, 8, 8)
		let width = self.tableView.width - 2*20 - margins.left - margins.right
		let size = CGSize(width: width, height: CGFloat.infinity)
		let height = self.drop.content.attributedText.boundingRect(with: size, options: .usesLineFragmentOrigin, context: nil).height
		let calculated = height + margins.top + margins.bottom + 2*20
		let display = self.view.height - self.toolbar.height - 100
		return min(calculated, display)
	}()
    
	fileprivate var contentCell: DropContentCell!
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
		
		authorNameLabel.text = drop.author.name
		dateLabel.text = drop.date.shortText
		
		imageView.image = UIImage.named(drop.image)

		tableView.reloadData()
    }
    
    @IBAction func toolbarButtonClicked(_ sender: UIButton){
        let index = toolbarButtons.index(of: sender)!
        
        switch index {
        case 0:
            drop.isLiked = !drop.isLiked
            drop.likes += drop.isLiked ? 1 : -1
            let icon = drop.isLiked ? "toolbar_heart_solid" : "toolbar_heart"
            sender.setImage(UIImage.named(icon), for: .normal)
            sender.setTitle("\(drop.likes)", for: .normal)
        case 1:
            let indexPath = IndexPath(row: 0, section: 1)
            tableView.scrollToRow(at: indexPath, at: .top, animated: true)
        default: break
        }
    }
    
    @objc fileprivate func likeBtnClicked(_ sender: UIButton){
        if let cell = sender.superview?.superview?.superview as? CommentCell,
            let indexPath = tableView.indexPath(for: cell) {
            let model = commentModel(for: indexPath)
            model.isLiked = !model.isLiked
            model.likes += model.isLiked ? 1 : -1
            cell.comment = model
        }
    }
    
    @IBAction func commentBtnClicked(_ sender: UIButton){
        if let cell = sender.superview?.superview?.superview as? CommentCell,
            let indexPath = tableView.indexPath(for: cell) {
            let model = commentModel(for: indexPath)
			if let parentComment = parentFor(comment: model){
				showCommentBox(toUser: model.author, parentComment: parentComment)
			}
        }
		else{
			showCommentBox(toUser: nil, parentComment: nil)
		}
    }
	
	func showCommentBox(toUser: User?, parentComment: Comment?) {
		if let vc: CommentVC = .make(from: .main){
			vc.toUser = toUser
			vc.comment = parentComment
			vc.modalTransitionStyle = .crossDissolve
			vc.modalPresentationStyle = .overCurrentContext
			present(vc: vc)
		}
	}
	
	func parentFor(comment: Comment) -> Comment? {
		var parentComment: Comment? = comment
		if comment.parentId != 0{
			parentComment = comments.filter{
				$0.id == comment.parentId
			}.first
		}
		return parentComment
	}
	
	func indexPath(forComment comment: Comment) -> IndexPath?{
		var parentComment: Comment? = comment
		if comment.parentId != 0 {
			parentComment = comments.filter{
				$0.id == comment.parentId
			}.first
		}
		if let section = comments.index(of: parentComment!){
			guard let row = parentComment!.replies.index(of: comment) else{
				return IndexPath(row: 0, section: section + 2)
			}
			return IndexPath(row: row + 1, section: section + 2)
		}
		return nil
	}
	
	@IBAction func unwindDropDetailVC(_ sender: UIStoryboardSegue) {
		if let vc = sender.source as? CommentVC,
			let text = vc.textView.text{
			let comment = Comment()
			comment.content = text
			comment.id = Int(arc4random_uniform(10000))
			comment.author.name = "用户_\(comment.id)"
			if let user = vc.toUser{
				comment.toUser = user
			}
			if let parentComment = vc.comment{
				comment.parentId = parentComment.id
				parentComment.replies.append(comment)
				if let indexPath = indexPath(forComment: comment) {
					tableView.insertRows(at: [indexPath], with: .automatic)
					tableView.reloadSections(.with(indexPath.section), with: .none)
					tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
				}
			}
			else{
				comments.append(comment)
				if let indexPath = indexPath(forComment: comment) {
					tableView.insertSections(.with(indexPath.section), with: .automatic)
					tableView.scrollToRow(at: indexPath, at: .middle, animated: true)
				}
			}
		}
	}
}

extension DropDetailVC: UIScrollViewDelegate{
	func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let cell = contentCell else {
            return
        }
		if scrollView == cell.textView{
			if scrollView.isTopHit || scrollView.isBottomHit{
				scrollView.isUserInteractionEnabled = false
			}
			else{
				scrollView.isUserInteractionEnabled = true
			}
		}
		else{
			cell.textView.isUserInteractionEnabled = true
		}
	}
}

extension DropDetailVC: UITableViewDelegate{
	func commentModel(for indexPath: IndexPath) -> Comment {
		let section = indexPath.section
		let row = indexPath.row
		let comment = comments[section - 2]
		let replies = comment.replies
		return row == 0 ? comment : replies[row - 1]
	}
	
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section > 1 else {
            return
        }
		
		func deleteDialog(){
			Dialog.default(title: .init("确定要删除该条评论?"), message: .init("删除后不可恢复"), actions:[
				.init(title: "删除", style: .destructive, handler: {_ in
					
				}),
				.init(title: "取消", style: .cancel)
			])
		}
		
		let configuration  = Dialog.Configuration()
		configuration.isBackgroundViewUserInteractionEnabled = true
		Dialog.default(actions: [
			.init(title: "删除", style: .destructive, handler: {
				_ in
				deleteDialog()
			}),
			.init(title: "分享"),
			.init(title: "举报"),
			.init(title: "屏蔽")
		], configuration: configuration)
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 {
            return 80
        }
        return indexPath.section == 0
            ? contentHeight
            : UITableViewAutomaticDimension
    }
}

extension DropDetailVC: UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return comments.count + 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		switch section {
		case 0, 1:
			return 1
		default:
			return comments[section - 2].replies.count + 1
		}
    }
	
	func contentCell(for indexPath: IndexPath) -> UITableViewCell {
		if contentCell == nil {
			contentCell = tableView.dequeueCell(withClass: DropContentCell.self, for: indexPath)!
			contentCell.textView.attributedText = drop.content.attributedText
		}
		return contentCell
	}
	
	func  commentCell(for indexPath: IndexPath) -> UITableViewCell {
		var cell: CommentCell!
		
		let model = commentModel(for: indexPath)
		
		// 评论
		if model.parentId == 0{
			cell = tableView.dequeueCellFrom(nib: "CommentCell", reuseId: "CommentCell") as! CommentCell
			var margins = cell.contentView.layoutMargins
            margins.bottom = model.replies.isEmpty ? 10 : 0.5
			cell.contentView.layoutMargins = margins
		}
		// 回复
		else{
			cell = tableView.dequeueCellFrom(nib: "CommentCell", reuseId: "CommentCellReply", index: 1) as! CommentCell
			let parent = parentFor(comment: model)!
			let index = parent.replies.index(of: model)!
			var margins = cell.contentView.layoutMargins
			margins.bottom = index == (parent.replies.count - 1) ? 10 : 0.5
			cell.contentView.layoutMargins = margins
		}
		
		cell.comment = model
		
		cell.commentBtn.addTarget(self, action: #selector(commentBtnClicked(_:)), for: .touchUpInside)
		cell.likeBtn.addTarget(self, action: #selector(likeBtnClicked(_:)), for: .touchUpInside)
		
		return cell
	}
	
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		
		let section = indexPath.section
		switch section {
		case 0:
			return contentCell(for: indexPath)
		case 1:
			let cell = tableView.dequeueReusableCell(withIdentifier: "CommentAddCell", for: indexPath)
			return cell
		default:
			return commentCell(for: indexPath)
		}
    }
}
